import React, { Component } from 'react'
import _ from 'lodash'
import { Input, InputNumber, Radio, Space, Tooltip } from 'antd'
import TheDialog from '@/components/TheDialog'
import TheLocations from '@/components/TheLocations'
import TheTable from '@/components/TheTable'
import TheButton from '@/components/TheButton'

export default class EditTemplate extends Component {
  state = {
    weightColumns: [
      {
        title: '运送到',
        dataIndex: 'area',
        key: 'area',
        render: (text, record, index) => {
          return <div>
            <Tooltip title={text}>
              <div className='p-white-space' style={{
                width: 120,
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }}>{text}</div>
            </Tooltip>
            <TheButton onClick={() => this.setState({
              locationIndex: index,
              locationVisible: true,
              selectArea: {
                area: this.state.weightDataSource[index].area,
                areaId: this.state.weightDataSource[index].areaId,
              }
            })}>编辑</TheButton>
          </div>
        }
      },
      {
        title: '首重量（kg）',
        dataIndex: 'firstCompany',
        key: 'firstCompany',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setWeightData(e, index, 'firstCompany')}
            precision={1} min={0} value={text} />
        }
      },
      {
        title: '首费（元）',
        dataIndex: 'firstPrice',
        key: 'firstPrice',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setWeightData(e, index, 'firstPrice')}
            precision={2} min={0} value={text} />
        }
      },
      {
        title: '续重量（kg）',
        dataIndex: 'continuedCompany',
        key: 'continuedCompany',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setWeightData(e, index, 'continuedCompany')}
            precision={1} min={0} value={text} />
        }
      },
      {
        title: '续费（元）',
        dataIndex: 'continuedPrice',
        key: 'continuedPrice',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setWeightData(e, index, 'continuedPrice')}
            precision={2} min={0} value={text} />
        }
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record, index) => {
          return <TheButton onClick={() => this.delData(index, 'weightDataSource')}>删除</TheButton>
        }
      }
    ],
    numColumns: [
      {
        title: '运送到',
        dataIndex: 'area',
        key: 'area',
        render: (text, record, index) => {
          return <div>
            <Tooltip title={text}>
              <div className='p-white-space' style={{
                width: 120,
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }}>{text}</div>
            </Tooltip>
            <TheButton onClick={() => this.setState({
              locationIndex: index,
              locationVisible: true,
              selectArea: {
                area: this.state.numDataSource[index].area,
                areaId: this.state.numDataSource[index].areaId,
              }
            })}>编辑</TheButton>
          </div>
        }
      },
      {
        title: '首件数',
        dataIndex: 'firstCompany',
        key: 'firstCompany',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setNumData(e, index, 'firstCompany')}
            precision={0} min={0} value={text} />
        }
      },
      {
        title: '首费（元）',
        dataIndex: 'firstPrice',
        key: 'firstPrice',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setNumData(e, index, 'firstPrice')}
            precision={2} min={0} value={text} />
        }
      },
      {
        title: '续件',
        dataIndex: 'continuedCompany',
        key: 'continuedCompany',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setNumData(e, index, 'continuedCompany')}
            precision={0} min={0} value={text} />
        }
      },
      {
        title: '续费（元）',
        dataIndex: 'continuedPrice',
        key: 'continuedPrice',
        render: (text, record, index) => {
          return <InputNumber
            onChange={e => this.setNumData(e, index, 'continuedPrice')}
            precision={2} min={0} value={text} />
        }
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record, index) => {
          return <TheButton onClick={() => this.delData(index, 'numDataSource')}>删除</TheButton>
        }
      }
    ],
    defaultWeight: {
      area: '-1',
      areaId: '-1',
      firstCompany: null,
      firstPrice: null,
      continuedCompany: null,
      continuedPrice: null
    },
    defaultNum: {
      area: '-1',
      areaId: '-1',
      firstCompany: null,
      firstPrice: null,
      continuedCompany: null,
      continuedPrice: null
    },
    weightDataSource: [],
    numDataSource: [],
    locationVisible: false,
    freightTemplateName: '',
    pricingMethod: 'FREE',
    areaObj: {},
    locationIndex: null,
    selectArea: {},
    freightTemplateId: ''
  }
  componentDidMount() {
    this.initData(this.props.editValue)
  }
  initData = value => {
    const { freightTemplateName, pricingMethod, freightTemplateId, freightTemplateChildList } = value
    let data = []
    let defaultData = {}
    let name = ''
    let defaultName = ''
    switch (pricingMethod) {
      case 'FREE':
        break;
      case 'WEIGHT':
        name = 'weightDataSource';
        defaultName = 'defaultWeight';
        _.forEach(freightTemplateChildList, v => {
          v = {
            area: v.area,
            areaId: v.areaId,
            firstCompany: React.$transNum(v.firstCompany, 1, -3),
            firstPrice: React.$transNum(v.firstPrice, 2, -2),
            continuedCompany: React.$transNum(v.continuedCompany, 1, -3),
            continuedPrice: React.$transNum(v.continuedPrice, 2, -2)
          }
          if (v.area === '-1') {
            defaultData = v
          } else {
            data.push(v)
          }
        })
        break;
      case 'NUM':
        name = 'numDataSource';
        defaultName = 'defaultNum';
        _.forEach(freightTemplateChildList, v => {
          v = {
            area: v.area,
            areaId: v.areaId,
            firstCompany: v.firstCompany,
            firstPrice: React.$transNum(v.firstPrice, 2, -2),
            continuedCompany: v.continuedCompany,
            continuedPrice: React.$transNum(v.continuedPrice, 2, -2)
          }
          if (v.area === '-1') {
            defaultData = v
          } else {
            data.push(v)
          }
        })
        break;
    }

    this.setState({
      [name]: data,
      [defaultName]: defaultData,
      freightTemplateName,
      pricingMethod,
      freightTemplateId
    })
  }
  addRadioChange = e => {
    this.setState({
      pricingMethod: e.target.value
    })
  }
  getArea = areaObj => {
    this.setState({
      areaObj
    })
  }
  addWeight = () => {
    if (!_.every(this.state.defaultWeight)) {
      return React.$message({
        type: 'error',
        content: '请填写完整的默认运费模板'
      })
    }
    let weightDataSource = [...this.state.weightDataSource, {
      area: '',
      areaId: '',
      firstCompany: null,
      firstPrice: null,
      continuedCompany: null,
      continuedPrice: null
    }]
    this.setState({
      weightDataSource
    })
  }
  addNum = () => {
    if (!_.every(this.state.defaultNum)) {
      return React.$message({
        type: 'error',
        content: '请填写完整的默认运费模板'
      })
    }
    let numDataSource = [...this.state.numDataSource, {
      area: '',
      areaId: '',
      firstCompany: null,
      firstPrice: null,
      continuedCompany: null,
      continuedPrice: null
    }]
    this.setState({
      numDataSource
    })
  }
  setWeightData = (value, index, name) => {
    let data = _.cloneDeep(this.state.weightDataSource)
    data.splice(index, 1, {
      ...this.state.weightDataSource[index],
      [name]: value
    })
    this.setState({
      weightDataSource: data
    })
  }
  setNumData = (value, index, name) => {
    let data = _.cloneDeep(this.state.numDataSource)
    data.splice(index, 1, {
      ...this.state.numDataSource[index],
      [name]: value
    })
    this.setState({
      numDataSource: data
    })
  }
  locationSave = () => {
    const { locationIndex, areaObj, pricingMethod } = this.state
    let label = ''
    switch (pricingMethod) {
      case 'WEIGHT':
        label = 'weightDataSource'
        break
      case 'NUM':
        label = 'numDataSource'
        break
    }
    let data = _.cloneDeep(this.state[`${label}`])
    data.splice(locationIndex, 1, {
      ...data[locationIndex],
      ...areaObj
    })
    React.$message({
      type: 'info',
      content: '编辑城市成功'
    })
    this.setState({
      [`${label}`]: data,
      locationVisible: false
    })
  }
  getValue = () => {
    const { weightDataSource, defaultWeight, freightTemplateName, pricingMethod, defaultNum, numDataSource, freightTemplateId } = this.state
    //包邮
    if (!freightTemplateName) {
      return React.$message({
        type: 'error',
        content: '请填写模板名称'
      })
    }
    if (pricingMethod === 'FREE') {
      return {
        freightTemplateName,
        pricingMethod
      }
    }
    //计重
    if (pricingMethod === 'WEIGHT') {
      let status = true
      let data = _.cloneDeep(weightDataSource)
      data.unshift(defaultWeight)
      _.forEach(data, v => {
        if (!_.every(v)) {
          return status = false
        }
      })
      if (!status) {
        return React.$message({
          type: 'error',
          content: '请填写完整的模板信息'
        })
      } else {
        let freightTemplateChildList = data.map(v => {
          return {
            ...v,
            firstCompany: React.$transNum(v.firstCompany, 0, 3),
            firstPrice: React.$transNum(v.firstPrice, 0, 2),
            continuedCompany: React.$transNum(v.continuedCompany, 0, 3),
            continuedPrice: React.$transNum(v.continuedPrice, 0, 2)
          }
        })
        return {
          freightTemplateName,
          pricingMethod,
          freightTemplateChildList,
          freightTemplateId
        }
      }
    }
    //计件
    if (pricingMethod === 'NUM') {
      let status = true
      let data = _.cloneDeep(numDataSource)
      data.unshift(defaultNum)
      _.forEach(data, v => {
        if (!_.every(v)) {
          return status = false
        }
      })
      if (!status) {
        return React.$message({
          type: 'error',
          content: '请填写完整的模板信息'
        })
      } else {
        let freightTemplateChildList = data.map(v => {
          return {
            ...v,
            firstPrice: React.$transNum(v.firstPrice, 0, 2),
            continuedPrice: React.$transNum(v.continuedPrice, 0, 2)
          }
        })
        return {
          freightTemplateName,
          pricingMethod,
          freightTemplateChildList,
          freightTemplateId
        }
      }
    }
  }
  delData = (index, name) => {
    React.$confirm({
      title: '您确认删除此项吗？',
      onOk: () => {
        let data = _.cloneDeep(this.state[name])
        _.remove(data, (v, i) => i === index)
        this.setState({
          [name]: data
        })
      }
    })
  }
  render() {
    const { weightColumns, locationVisible, freightTemplateName, pricingMethod, weightDataSource, defaultWeight: { firstCompany, firstPrice, continuedCompany, continuedPrice }, numDataSource, selectArea, defaultNum, numColumns } = this.state
    return (
      <div>
        <div>
          <div className='distribution-label'>
            <span>模板名称</span>
            <Input
              maxLength={20}
              style={{ width: 200 }}
              onChange={e => this.setState({ freightTemplateName: e.target.value })}
              defaultValue={freightTemplateName}
              value={freightTemplateName}
              placeholder="请输入模板名称" />
          </div>
          <div className='distribution-label'>
            <span>计价方式</span>
            <Radio.Group value={pricingMethod} onChange={this.addRadioChange}>
              <Radio value={'FREE'}>包邮</Radio>
              <Radio value={'WEIGHT'}>计重</Radio>
              <Radio value={'NUM'}>计件</Radio>
            </Radio.Group>
          </div>
          {/* 计重 */}
          {pricingMethod === 'WEIGHT' && <div>
            <div className='distribution-label template'>
              <span>默认运费</span>
              <Space>
                <InputNumber
                  precision={1}
                  min={0}
                  value={firstCompany}
                  addonAfter="kg内"
                  onChange={e => this.setState({ defaultWeight: { ...this.state.defaultWeight, firstCompany: e } })}
                  style={{ width: 135 }} />

                <InputNumber
                  precision={2}
                  min={0}
                  value={firstPrice}
                  onChange={e => this.setState({ defaultWeight: { ...this.state.defaultWeight, firstPrice: e } })}
                  addonAfter="元"
                  style={{ width: 125 }} />

                <InputNumber
                  precision={1}
                  min={0}
                  value={continuedCompany}
                  onChange={e => this.setState({ defaultWeight: { ...this.state.defaultWeight, continuedCompany: e } })}
                  addonAfter="kg"
                  addonBefore="每增加"
                  style={{ width: 175 }} />

                <InputNumber
                  precision={2}
                  min={0}
                  value={continuedPrice}
                  onChange={e => this.setState({ defaultWeight: { ...this.state.defaultWeight, continuedPrice: e } })}
                  addonAfter="元"
                  addonBefore="增加运费"
                  style={{ width: 185 }} />
              </Space>
            </div>
            {_.size(weightDataSource) > 0 && <TheTable columns={weightColumns} dataSource={weightDataSource} />}
            <div className='template-footer'>
              <TheButton onClick={this.addWeight}>+为指定地区设置运费</TheButton>
              <div>除指定地区外，其余地区采用“默认运费”</div>
            </div>
          </div>}
          {/* 计件 */}
          {pricingMethod === 'NUM' && <div>
            <div className='distribution-label template'>
              <span>默认运费</span>
              <Space>
                <InputNumber
                  precision={0}
                  min={0}
                  value={defaultNum.firstCompany}
                  addonAfter="件内"
                  onChange={e => this.setState({ defaultNum: { ...this.state.defaultNum, firstCompany: e } })}
                  style={{ width: 135 }} />

                <InputNumber
                  precision={2}
                  min={0}
                  value={defaultNum.firstPrice}
                  onChange={e => this.setState({ defaultNum: { ...this.state.defaultNum, firstPrice: e } })}
                  addonAfter="元"
                  style={{ width: 125 }} />

                <InputNumber
                  precision={0}
                  min={0}
                  value={defaultNum.continuedCompany}
                  onChange={e => this.setState({ defaultNum: { ...this.state.defaultNum, continuedCompany: e } })}
                  addonAfter="件"
                  addonBefore="每增加"
                  style={{ width: 175 }} />

                <InputNumber
                  precision={2}
                  min={0}
                  value={defaultNum.continuedPrice}
                  onChange={e => this.setState({ defaultNum: { ...this.state.defaultNum, continuedPrice: e } })}
                  addonAfter="元"
                  addonBefore="增加运费"
                  style={{ width: 185 }} />
              </Space>
            </div>
            {_.size(numDataSource) > 0 && <TheTable columns={numColumns} dataSource={numDataSource} />}
            <div className='template-footer'>
              <TheButton onClick={this.addNum}>+为指定地区设置运费</TheButton>
              <div>除指定地区外，其余地区采用“默认运费”</div>
            </div>
          </div>}
        </div>
        <TheDialog
          title="城市地区"
          visible={locationVisible}
          handleCancel={() => this.setState({ locationVisible: false, dataIndex: null, areaObj: {} })}
          handleOk={this.locationSave}
        >
          <TheLocations selectArea={selectArea} getArea={this.getArea} />
        </TheDialog>
      </div>
    )
  }
}
